package cn.com.srit.controller;

import cn.com.srit.entity.DeptEntity;
import cn.com.srit.service.DeptService;
import cn.com.srit.util.PageDetailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/dept/findAll", method = RequestMethod.GET)
    public Map<String, Object> findAll(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        result.put("depts", deptService.findAll(getTemplate(request)));
        return result;
    }

    @RequestMapping(value = "/dept/findAllWithPage", method = RequestMethod.GET)
    public Map<String, Object> findAllWithPage(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Page<DeptEntity> deptsWithPage = deptService.findAllWithPage(getTemplate(request), PageDetailUtils.getPageDetail(request));
        result.put("total", deptsWithPage.getTotalElements());
        result.put("rows", deptsWithPage.getContent());
        return result;
    }

    @RequestMapping(value = "/dept/save", method = RequestMethod.POST)
    public Map<String, Object> save(DeptEntity dept) {
        Map<String, Object> result = new HashMap<>();
        result.put("status", deptService.save(dept));
        return result;
    }

    @RequestMapping(value = "/dept/delete", method = RequestMethod.POST)
    public Map<String, Object> delete(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        result.put("status", deptService.delete(request.getParameter("ids").split(",")));
        return result;
    }

    private DeptEntity getTemplate(HttpServletRequest request) {
        DeptEntity template = new DeptEntity();
        try {
            Field[] fields = template.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String fieldValue = request.getParameter(field.getName());
                if (StringUtils.hasText(fieldValue)) {
                    field.set(template, fieldValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return template;
    }
}
